<template>
  <div class="report-container">
    <iframe id="exportPdf" width="0" height="0" />
    <div id="picture_print">
      <h1 class="report-title">大功率机车运行质量检修报告</h1>
      <div class="info-row" style="margin-left: 0px; display: flex; flex-wrap: wrap; justify-content: flex-start;">
        <div class="info-col" style="margin-left: 0px; flex: 0 0 25%; max-width: 25%;">
          车型：{{ dataTrainType }}
        </div>
        <div class="info-col" style="flex: 0 0 25%; max-width: 25%;">
          车号：{{ dataTrainNum }}
        </div>
        <div class="info-col" style="flex: 0 0 25%; max-width: 25%;">
          所在端：{{ dataTrainDuan }}
        </div>
        <div class="info-col" style="flex: 0 0 25%; max-width: 25%;">
          报表时间：{{ dataTrainTime }}
        </div>
      </div>
    </div>
    <div id="print-table" class="table-container" :class="{'printToPdf': isPrintToPdfFlag}">
      <!-- 详细报告表格 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%;margin-left: 30px"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column prop="id" label="序号" width="180" />
        <el-table-column prop="system" label="所属系统" width="180" />
        <el-table-column prop="result" label="检测结果" />
      </el-table>
    </div>
    <el-button style="margin-top: 10px; margin-left: 30px" type="primary" @click="exportpdfwordex">打印报表</el-button>
    <el-button style="margin-top: 10px; margin-left: 50px" type="primary" @click="handleClick">详细报表</el-button>
    <el-dialog
      :visible.sync="dialogVisible"
      width="70%"
    >
      <detail-report></detail-report>
      </el-dialog>
  </div>
</template>

<script>
import detailReport from './detailReport'
import DetailReport from '@/views/inspereport/components/detailReport.vue'
export default {
  components: { DetailReport },
  comments: { detailReport },
  data() {
    return {
      dialogVisible: false,
      isPrintToPdfFlag: false,
      dataTrainType: 'HXD3B',
      dataTrainNum: '1234',
      dataTrainDuan: 'A端',
      dataTrainTime: '2024-11-11 16:30:30',
      tableData: [
        { id: 1, system: '网络控制系统', result: '正常' },
        { id: 2, system: '牵引变流系统', result: '正常' },
        { id: 3, system: '辅助变流系统', result: '正常' },
        { id: 4, system: '空气制动系统', result: '正常' },
        { id: 5, system: '其它关键部件', result: '正常' }
      ]
    }
  },
  methods: {
    handleClick(component) {
      // 使用this.$router.resolve来获取完整的路由URL
      const route = this.$router.resolve({ path: '/detailReport', query: { data: 'nihao' } });

      // 获取解析后的URL
      const routeUrl = route.href

      // 在新标签页中打开URL
      window.open(routeUrl, '_blank') // '_blank' 表示在新标签页中打开
    },
    exportpdfwordex() {
      // this.trainloading = true
      // console.log('ceshi', 'ceshi22')
      this.setTableStyle()
      // eslint-disable-next-line no-undef
      // console.log('ceshi', 'ceshi11')
      this.setTableStyle()
      const iframe = document.getElementById('exportPdf')
      const doc = iframe.contentWindow.document
      // #print-table是自己的外层id
      const tcontent = document.querySelector('#print-table .el-table').innerHTML // 获取table表中数据
      const contentpic = document.getElementById('picture_print').innerHTML
      // console.log('tcontent',tcontent)
      //  let tcontent_p='<div><h1 style="text-align: center">深圳14号线列车限界检测报告</h1></div>'+tcontent+'<div><h2 style="text-align: right">检测结果: &nbsp; &nbsp; &nbsp;'+this.detect_result+' &nbsp; &nbsp; &nbsp; </h2><h2 style="text-align: right">部门名称:_____________</h2><h2 style="text-align: right">签字确认:_____________</h2><h2 style="text-align: right">日期时间:_____________</h2></div>'
      const tcontent_p = contentpic + tcontent
      // &nbsp; &nbsp; &nbsp;
      // console.log('tcontent_p',tcontent_p)
      // 将获取到html标签数据赋值给iframe中组件中id中，组件的样式将影响html标签数据
      doc.getElementsByTagName('body')[0].innerHTML = tcontent_p

      iframe.contentWindow.print() // 调取iframe打印，数据过多打印会自动分页
      this.clearTableStyle()
      // this.trainloading = false
    },
    setTableStyle() {
      // table-designer-container是我自己的外层class，换成你自己的！！！！！！！！！！！！！！！
      const tableDomList = document
        .querySelector('.table-container')
        .getElementsByTagName('table')
      // console.log('tableDomList',tableDomList)
      // 去除element的覆盖层
      this.isPrintToPdfFlag = true
      const headRightTh_ = tableDomList[0]
        .getElementsByTagName('tr')[0]
        .getElementsByTagName('th')

      // console.log('headRightTh_',headRightTh_)
      headRightTh_[headRightTh_.length - 1].style.borderRight = '1px solid #ABABAB'
      // headRightTh_[headRightTh_.length - 1].style.fontSize = '40px'
      /*
      const headRightTh = tableDomList[0]
        .getElementsByTagName('tr')[1]
        .getElementsByTagName('th')

      //  console.log('headRightTh',headRightTh)
      headRightTh[headRightTh.length - 2].style.borderRight =
        '1px solid #ABABAB'
      // console.log('hello20',1)
      */
      // 遍历两个table
      const tableLength = tableDomList.length
      // console.log('headRightTh_length',tableLength)
      for (let i = 0; i < tableLength; i++) {
        tableDomList[i].setAttribute('border', '1')
        tableDomList[i].style.border = '#ffffff'
        const childTr = tableDomList[i].getElementsByTagName('tr')
        const childTrLength = childTr.length
        // console.log('hello20',2)
        // 第一个table是头部，没有td会报错
        if (i > 0) {
          for (let j = 0; j < childTrLength; j++) {
            const childTd = childTr[j].getElementsByTagName('td')
            const childTdLength = childTd.length
            // 修改最后一个的边框值
            // console.log('childTdLength',childTdLength)
            // console.log('childTd',childTd)
            // console.log('childTd[childTdLength - 1].style)',childTd[childTdLength - 1])
            if (childTdLength > 0 && childTd[childTdLength - 1].style) {
              childTd[childTdLength - 1].style.borderRight =
                '1px solid #ABABAB'
            }
            //  console.log('hello20',20)
            for (let k = 0; k < childTdLength; k++) {
              childTd[k].style.padding = '8px 0' // 改变之后与element高度一致
              childTd[k].style.valign = 'center'
              childTd[k].style.align = 'center'
              childTd[k].style.textAlign = 'center'

              // eslint-disable-next-line eqeqeq
              if (j == childTrLength - 1) {
                childTd[k].style.borderBottom = '1px solid #ABABAB'
              }
            }
          }
        } else {
          // 去除第一个table去除最右侧的空白th
          const childTr = tableDomList[i].getElementsByTagName('tr')
          const childTrLength = childTr.length
          for (let i = 0; i < childTrLength; i++) {
            const lastTh = childTr[i].querySelector('.gutter')
            if (lastTh) {
              lastTh.parentNode.removeChild(lastTh)
            }
          }
        }
      }

      // print-table是我自己的外层id，换成你自己的id
      return document.querySelector('#print-table .el-table').innerHTML
    },
    // todo清除表格样式
    clearTableStyle() {
      // table-designer-container是我自己的外层class，换成你自己的！！！！！！！！！！！！！！！
      // console.log('hello0',0)
      const tableDomList = document
        .querySelector('.table-container')
        .getElementsByTagName('table')

      // 去除第一个table表头最右侧的边框
      /*
      const headRightTh = tableDomList[0]
        .getElementsByTagName('tr')[1]
        .getElementsByTagName('th')
      headRightTh[headRightTh.length - 2].style.borderRight = '1px solid #EBEEF5'
      // console.log('hello2',2)
*/
      const headRightTh_ = tableDomList[0]
        .getElementsByTagName('tr')[0]
        .getElementsByTagName('th')
      //  console.log('headRightTh_',headRightTh_)
      //  console.log('hello4',4)
      headRightTh_[headRightTh_.length - 1].style.borderRight = '1px solid #EBEEF5'
      //   console.log('hello5',5)
      headRightTh_[headRightTh_.length - 1].style.fontSize = '15px'
      //   console.log('hello3',3)
      // 去除右侧和最底部的样式
      for (let i = 0; i < tableDomList.length; i++) {
        tableDomList[i].setAttribute('border', '0')
        tableDomList[i].style.border = 'none'
        const childTr = tableDomList[i].getElementsByTagName('tr')
        const childTrLength = childTr.length
        // 第一个table是头部，没有td会报错
        if (i > 0) {
          for (let j = 0; j < childTrLength; j++) {
            const childTd = childTr[j].getElementsByTagName('td')
            const childTdLength = childTd.length
            // 修改最后一个的边框值
            if (childTdLength > 0 && childTd[childTdLength - 1].style) {
              childTd[childTdLength - 1].style.borderRight = 'none'
            }
            for (let k = 0; k < childTdLength; k++) {
              // eslint-disable-next-line eqeqeq
              if (j == childTrLength - 1) {
                childTd[k].style.borderBottom = '1px solid #EBEEF5'
              }
            }
          }
        }
      }
    },

    printReport() {
      const printContents = document.getElementById('printTable').innerHTML

      // 创建一个新的iframe用于打印
      const iframe = document.createElement('iframe')
      iframe.style.position = 'absolute'
      iframe.style.left = '-10000px'
      document.body.appendChild(iframe)

      // 获取iframe的文档对象
      const iframeDoc = iframe.contentWindow ? iframe.contentWindow.document : iframe.contentDocument

      // 将需要打印的内容写入iframe
      iframeDoc.open()
      iframeDoc.write(`
        <html>
          <head>
            <title>打印报表</title>
            <style>
              body {
                font-family: Arial, sans-serif;
                line-height: 1.5;
              }
              .report-title {
                font-weight: bold;
                text-align: center;
                margin-bottom: 20px;
              }
              .info-row {
                margin-bottom: 20px;
              }
              .info-col {
                text-align: center;
              }
              .el-table {
                border: 2px solid #000;
                width: 100%;
              }
              .el-table th,
              .el-table td {
                border: 2px solid #000;
                text-align: center;
              }
              .el-table th > .cell {
                font-weight: bold;
                color: #333;
              }
              .el-table th.gutter,
              .el-table td.gutter {
                display: none; /* 隐藏默认的扩展列 */
              }
              .el-table .el-table__empty-block {
                display: none; /* 隐藏空数据提示 */
              }
            </style>
          </head>
          <body>
            ${printContents}
          </body>
        </html>
      `)
      iframeDoc.close()

      // 延迟一段时间后打印，并移除iframe
      setTimeout(() => {
        try {
          iframe.contentWindow.print()
        } catch (error) {
          console.error('打印失败:', error)
        } finally {
          document.body.removeChild(iframe)
        }
      }, 1000) // 确保iframe加载完成后再打印
    }
  }
}
</script>

<style scoped>
.report-container {
  padding: 20px;
}

.report-title {
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
}

.info-row {
  margin-bottom: 20px;
}

.info-col {
  text-align: center;
  padding: 10px; /* 增加内边距以改善布局 */
}

/* 表格样式 */
.el-table {
  border: 2px solid #000; /* 设置表格边框为2px的实线，颜色为黑色 */
}

.el-table th,
.el-table td {
  border: 2px solid #000; /* 设置表头和单元格的边框为2px的实线，颜色为黑色 */
  text-align: center;
}

.el-table th > .cell {
  font-weight: bold;
  color: #333;
}

/* 重置Element UI表格的默认边框样式 */
.el-table--border::after,
.el-table--group::after,
.el-table::before {
  background-color: transparent;
}

/* 去除表头底部边框 */
.el-table th.gutter,
.el-table td.gutter {
  display: none; /* 隐藏默认的扩展列 */
}

/* 去除表格行底部边框 */
.el-table .el-table__row td {
  border: none;
}

/* 隐藏空数据提示 */
.el-table .el-table__empty-block {
  display: none;
}
</style>
